#!/usr/bin/env bash

# PACKAGE: Gunther
# VERSION: 2.0
# DATE: 09/30/08
# AUTHOR(S): Zarrar Shehzad

# INCLUDE
source "$GUNTHERDIR/include/Asourceall.sh"

# VARIABLES
subject=""
iAnat=""
iFunc=""

# USAGE
function usage {
    changegood green
    echo "USAGE"
    echo "  $0 [OPTIONS] -i <subject> -m <input T1> -l <input EPI>"
    echo "program:"
    echo "   Moves raw data into appropriate folders (intended for data collected from NYU CBI)"
    echo "required options:"
    echo "  * -i; -m or -l"
    echo "available options are: "
    echo "  -i: subject id"
    echo "  -m: input T1 file"
    echo "  -l: input EPI file"
    standardUsage "$1"
    echo
    changebad
}

# PARSE OPTIONS
while getopts ":${standardOptList}i:m:l:"; do
    case $Option in
        i ) subject="$OPTARG"
            ;;
        m ) checkfile "$OPTARG"
            iAnat="$OPTARG"
            ;;
        l ) checkfile "$OPTARG"
            iFunc="$OPTARG"
            ;;
        * ) # Reference standard options found in y_options.sh
            standardOpts "$Option" "$OPTARG"
            ;;
    esac
done

# Give user feedback of what is running
ztitle "Executing: '$0 $@'"

# Move past any options
shift $((${OPTIND}-1))

# CHECK REQUIRED FILES GIVEN
## check for subject
if [[ -z "$subject" ]]; then
    zerror "You must specify a subject (-i)"
    exit -1
fi
## check for anat or func
if [[ -z "$iAnat" || -z "$iFunc" ]]; then
    zerror "You must specify an input anatomical or functional file"
    exit -1
fi
# If base directory doesn't exist, then end this
if [[ ! -d "${gDIR_DATA}" ]]; then
    zerror "Base preprocessing directory (${gDIR_DATA}) doesn't exist"
    exit -1
fi


# FUNCTIONS

function checkImage {
    fileType="$1"
    inputFile="$2"
    outputFile="$3"
    outputDir=`dirname ${outputFile}`
    
    if [[ ! -z "$inputFile" ]]; then
        # Create output directory
        if [[ ! -d "$outputDir" ]]; then
            zcmd "mkdir ${outputDir}"
        fi
        # Check output file
        checkfile "$outputFile" "return"
        if [[ "$?" = 0 ]]; then
            if [[ "$to_force" = 1 ]]; then
                znotice "Will overwrite existing ${fileType} image (${outputFile})"
                zcmd "rm ${to_confirm}${outputFile}"
            else
                zerror "${fileType} image already exists (${outputFile})...skipping"
                return 1
            fi
        fi
    fi
    
    return 0
}

function copyImage {
    isError="$?"
    inputFile="$1"
    outputFile="$2"
    
    zcmd "3dcopy ${inputFile} ${outputFile}"
    
    return "$?"
}


#
# BEGIN PROCESSING
#

ztitle "Setting up ${subject}"

# Get subject specific variables
source z_configSubject.sh

# Create subject directory if needed
if [[ ! -d ${iDir} ]]; then
    zcmd "mkdir ${iDir}"
fi

# CHECK
## anatomical
checkImage "anatomical" "$iAnat" "$mprage"
copyImage "$iAnat" "$mprage"
## functional
checkImage "functional" "$iFunc" "$funcRaw"
copyImage "$iFunc" "$funcRaw"

echo 
